package com.example.demo.control;

import com.example.demo.entity.Outpatient;
import com.example.demo.repository.OutpatientRepository;
import com.example.demo.utils.BackResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/outpatient")
public class OutpatientController {
    @Autowired
    private OutpatientRepository outpatientRepository;
//    分页查询
    @GetMapping("/findAllOutpatient")
    public Object list(Integer page, Integer pageSize){
        if (pageSize==null||page==null) {
            page=0;
            pageSize=15;
        }
        Object data = outpatientRepository.findAllByAny(page * pageSize, pageSize);
        int total=outpatientRepository.total();
        Map<String,Object> map =new HashMap<>();
        map.put("list",data);
        map.put("total",total);
        return BackResult.success(map);
    }

    /*
    * 添加门诊信息
    * */
    @PostMapping("/addOutpatient")
    public Object addOutpatient(Outpatient outpatient,String outpatientname){
       Outpatient data1= outpatientRepository.findAllByName(outpatientname);
        if (data1!=null){
            return  BackResult.fail("门诊已存在");
        }
        outpatient.set_live(1);
        Outpatient data=outpatientRepository.save(outpatient);
        if (data!=null){
            return   BackResult.success(data);
        }else {
            return  BackResult.fail("添加失败！");
        }
    }

    /*
    * 删除门诊信息
    * */
    @PostMapping("/removeOutpatient")
    public Object remove(Integer id){
        Outpatient outpatient = new Outpatient();
        outpatient.set_live(0);
        outpatient.setOutpatientid(id);

        Outpatient data= outpatientRepository.save(outpatient);
        if (data==null){
            return  BackResult.fail("门诊不存在");
        }
        return BackResult.success("删除成功！");
    }

    @PostMapping("/updateOutpatient")
    public  Object update(Integer id,String outpatientname){
        Outpatient data= outpatientRepository.findAllBy_live(id);
        if (data==null){
            return  BackResult.fail("门诊不存在");
        }
        data.set_live(1);
        data.setOutpatientname(outpatientname);
        outpatientRepository.save(data);
        return  BackResult.success(data);
    }
}
